package com.zzyl.serve.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.SecurityUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.serve.domain.AlertData;
import com.zzyl.serve.domain.Elder;
import com.zzyl.serve.domain.NursingElder;
import com.zzyl.serve.dto.AlertDataDto;
import com.zzyl.serve.dto.HandleAlertDataDto;
import com.zzyl.serve.mapper.AlertDataMapper;
import com.zzyl.serve.mapper.NursingElderMapper;
import com.zzyl.serve.service.IAlertDataService;
import com.zzyl.serve.service.IElderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;

/**
 * 报警数据Service业务层处理
 *
 * @author liuyp
 * @date 2025-08-26
 */
@Service
public class AlertDataServiceImpl extends ServiceImpl<AlertDataMapper, AlertData> implements IAlertDataService {
    @Autowired
    private AlertDataMapper alertDataMapper;
    @Autowired
    private IElderService elderService;
    @Autowired
    private NursingElderMapper nursingElderMapper;

    /**
     * 查询报警数据
     *
     * @param id 报警数据主键
     * @return 报警数据
     */
    @Override
    public AlertData selectAlertDataById(Long id) {
        return alertDataMapper.selectById(id);
    }

    /**
     * 查询报警数据列表
     *
     * @param dto 报警数据
     * @return 报警数据
     */
    @Override
    public TableDataInfo<AlertData> selectAlertDataList(AlertDataDto dto) {
//        查询条件
        LambdaQueryWrapper<AlertData> wrapper = Wrappers.<AlertData>lambdaQuery()
                .eq(StringUtils.isNotEmpty(dto.getDeviceName()), AlertData::getDeviceName, dto.getDeviceName())
                .between(dto.getStartTime() != null && dto.getEndTime() != null, AlertData::getCreateTime, dto.getStartTime(), dto.getEndTime())
                .eq(dto.getStatus()!=null,AlertData::getStatus, dto.getStatus());

//        开启分页并开始查询
        Page<AlertData> page = page(Page.of(dto.getPageNum(),dto.getPageSize()),wrapper);

//        根据员工id判断是否可以查看报警信息
        List<AlertData> records = page.getRecords();
        Long userId = SecurityUtils.getUserId();

        // 创建新的列表存储有权限查看的记录
        List<AlertData> filteredRecords = new ArrayList<>();

        for (AlertData record : records) {
            // 如果当前用户是管理员（ID为1）或者数据属于当前用户，则可以查看
            if (userId == 1 || userId.equals(record.getUserId())) {
                if (record.getLocationType()==0){
                    String accessLocation = record.getAccessLocation();
                    Elder byId = elderService.getById(Long.valueOf(accessLocation));
                    record.setAccessLocation(byId.getName());
                }
                filteredRecords.add(record);
            }
        }
//       将过滤后的记录替换原来的记录列表
        records = filteredRecords;

//        封装查询到的条件
        TableDataInfo<AlertData> tableDataInfo =  new TableDataInfo<>();
        tableDataInfo.setTotal(page.getTotal());
        tableDataInfo.setRows(records);
        tableDataInfo.setMsg("查询成功");
        tableDataInfo.setCode(HttpStatus.SUCCESS);


        return tableDataInfo;
    }

    /**
     * 新增报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int insertAlertData(AlertData alertData) {
        return alertDataMapper.insert(alertData);
    }

    /**
     * 修改报警数据
     *
     * @param alertData 报警数据
     * @return 结果
     */
    @Override
    public int updateAlertData(AlertData alertData) {
        return alertDataMapper.updateById(alertData);
    }

    /**
     * 批量删除报警数据
     *
     * @param ids 需要删除的报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataByIds(Long[] ids) {
        return alertDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除报警数据信息
     *
     * @param id 报警数据主键
     * @return 结果
     */
    @Override
    public int deleteAlertDataById(Long id) {
        return alertDataMapper.deleteById(id);
    }

    /**
     * 处理报警数据
     * @param dto 处理报警数据的员工,时间和备注
     */
    @Override
    public void handleAlertData(HandleAlertDataDto dto) {
//        根据修改的id查询老人id
        AlertData alertData = alertDataMapper.selectById(dto.getId());

//        补充需要修改的数据并封装
        Long userId = SecurityUtils.getUserId();
        String username = SecurityUtils.getUsername();
        dto.setProcessorId(userId);
        dto.setUserName(username);
        dto.setIotId(alertData.getIotId());

//        判断是否是随身设备
        if (alertData.getLocationType() == 0){
            String elderId = alertData.getAccessLocation();
//            根据老人id上面elderId查询所有的护理员的id,封装成一个集合
            Set<Long> nursingIds = nursingElderMapper.selectNurseIdsByElderId(elderId);
//            添加上管理员id
            nursingIds.add(1L);

            for (Long nursingId : nursingIds) {
                dto.setUserId(nursingId);
                alertDataMapper.updateHandAlerData(dto);
            }
        }
 //        将数据存入数据库
        alertDataMapper.updateHandAlerDataDto(dto);




    }
}
